import { AuthError } from '../types';
import { API_PATHS, getAuthHeaders, getBasicHeaders } from '../../../config/apiConfig';

export interface User {
  id: string;
  username: string;
  email: string;
  role: string;
  token?: string;
  avatar?: string;
  experience?: number; // 用户经验值
  passkey?: string; // 用户邀请码
}

export interface LoginCredentials {
  email: string;
  password: string;
}

export interface RegisterData {
  username: string;
  password: string;
  email: string;
  passkey: string; // 添加邀请码字段
}

export class AuthService {
  private static readonly STORAGE_KEY = 'auth_user';
  private static readonly TOKEN_KEY = 'token';
  private static readonly API_BASE = API_PATHS.auth;

  static async login(credentials: LoginCredentials): Promise<User> {
    const response = await fetch(`${this.API_BASE}/login`, {
      method: 'POST',
      headers: getBasicHeaders(),
      body: JSON.stringify(credentials)
    });

    if (!response.ok) {
      throw { type: 'auth', code: 'INVALID_CREDENTIALS' } as AuthError;
    }

    const userData = await response.json();
    
    // 保存token和用户信息
    if (userData.token) {
      localStorage.setItem(this.TOKEN_KEY, userData.token);
    }
    
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(userData));
    return userData;
  }

  static async register(data: RegisterData): Promise<any> {
    const response = await fetch(`${this.API_BASE}/register`, {
      method: 'POST',
      headers: getBasicHeaders(),
      body: JSON.stringify(data)
    });

    if (!response.ok) {
      const error = await response.json();
      if (error.message && error.message.includes('已存在')) {
        throw { type: 'auth', code: 'USERNAME_TAKEN' } as AuthError;
      }
      if (error.message && error.message.includes('邀请码')) {
        throw { type: 'auth', code: 'INVALID_PASSKEY' } as AuthError;
      }
      throw new Error(error.message || '注册失败');
    }

    // 返回注册成功的消息，不再自动登录
    return { success: true, message: '注册成功' };
  }

  static async getProfile(): Promise<User> {
    const response = await fetch(`${this.API_BASE}/profile`, {
      method: 'GET',
      headers: getAuthHeaders()
    });

    if (!response.ok) {
      throw new Error('获取用户信息失败');
    }

    const userData = await response.json();
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(userData));
    return userData;
  }

  static logout(): void {
    localStorage.removeItem(this.STORAGE_KEY);
    localStorage.removeItem(this.TOKEN_KEY);
  }

  static getCurrentUser(): User | null {
    const userJson = localStorage.getItem(this.STORAGE_KEY);
    return userJson ? JSON.parse(userJson) : null;
  }
}